const express = require('express');
const cors = require('cors');
const axios = require('axios');
const app = express();
const PORT = 4000;

// 允许跨域
app.use(cors());
// 中间件，解析 JSON 请求体
app.use(express.json());

// SSE 路由
app.get('/api/sse', (req, res) => {
    console.log('GET request received -- /api/sse');
    // 设置 SSE 头部
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // 发送初始消息
    res.write('data: Connected!\n\n');

    // 定时发送数据
    let count = 0;
    const timer = setInterval(() => {
        const data = {
            time: new Date().toISOString(),
            count: count++,
            message: 'Hello from SSE!'
        };
        res.write(`data: ${JSON.stringify(data)}\n\n`); // 必须用 \n\n 结尾
    }, 1000);

    // 客户端断开时清理
    req.on('close', () => {
        clearInterval(timer);
        res.end();
    });
});

// 健康检查端点（用于 Kubernetes）
app.get('/api/health', (req, res) => {
    console.log('GET request received -- /api/health');
    res.status(200).send('OK');
});

// 处理 GET 请求
app.get('/api/test', (req, res) => {
    console.log('GET request received -- /api/test');
    // res.send('Hello, this is a GET response!');
    
    // sse-service
    // axios.get('http://localhost:3000/api/test')
    axios.get('http://sse-service/api/test?k=' + req.query.k)
      .then((response) => {
        console.log('Response:', response.data);
        res.send(response.data);
      })
      .catch((error) => {
        console.error('请求遇到问题:', error);
      });
});

app.listen(PORT, () => {
    console.log(`SSE Server running on http://localhost:${PORT}/api/test`);
});